/*
 * Powered By [信安]
 * Since 2013 - 2013
 */


package com.xinan.system.curd;

import com.jfinal.aop.Before;
import com.jfinal.core.BaseController;
import com.jfinal.core.Const;
import com.jfinal.core.Controller;
import com.jfinal.ext.interceptor.SearchSql;
import com.jfinal.kit.JsonKit;
import com.jfinal.kit.StringKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.IAtom;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.jfinal.render.JsonRender;
import com.xinan.utils.Constants;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author EricLee
 * @version 1.0
 * @since 1.0
 */

public class AuthRoleController extends BaseController {

    public void index() {
        render("/WEB-INF/views/system/authRole.html");
    }

//    public void roles() {
//        render("system/authRole.html");
//    }

    /**
     * 在增加了SearchSql拦截之后，就可以根据页面的配置信息
     * 自动装配查询语句，并放入request中，可以通过getAttr(Const.SEARCH_SQL)函数获取到
     * 根据实际需要自动组装到sql语句中
     */
    @Before(SearchSql.class)
	public void query() {
        int pageNumber = getParaToInt("page");
        int pageSize = getParaToInt("rows");
        String where = getAttr(Const.SEARCH_SQL);
        String userName = getAttr(Constants.USER_NAME);
        if(StringKit.notBlank(where)){
            where += " and optname = '" + userName + "'";
        }else{
            where += " optname = '" + userName + "'";
        }

        Page<AuthRole> page = AuthRole.dao.page(pageNumber, pageSize, where);
        Map root = new HashMap();
     		// / jqgrid用 分页显示
     		root.put("total", page.getTotalRow());
     		root.put("rows", page.getList());
     		renderJson(JsonKit.toJson(root));
	}

	/**
     * 保存数据
     */
	public void save() {
        boolean flag = Db.tx(new IAtom() {
            @Override
            public boolean run() throws SQLException {
            String userName = getAttr(Constants.USER_NAME);
            AuthRole role = getModel(AuthRole.class);
            role.set("optname",userName);
            boolean sFlag = role.save();
            String perms = getPara("permIds");
            if(sFlag && StringKit.notBlank(perms)){
                String [] permIds = perms.split(",");
                String sql="insert into auth_role_permission(roleid, permissionid,optname) values (?,?,?)";
                int count = permIds.length;
                Object[][] params = new Object[count][3];
                for(int i=0;i<count;i++){
                    params[i][0]=role.getId();
                    params[i][1]=permIds[i];
                    params[i][2]=userName;
                }
                Db.batch(sql, params, count);
            }
            return sFlag;
            }
        });
        if(flag){
        //    renderJson(Constants.SAVESUCCESS);
			render(new JsonRender(Constants.SAVESUCCESS).forIE());

        }else{
       //     renderJson(Constants.SAVEFAILED);
			render(new JsonRender(Constants.SAVEFAILED).forIE());

        }
	}
	
	/**
     * Post请求的菜单更新函数，可以接受菜单的id和菜单对象，并根据菜单id进行更新，并返回影响行数，据此判断是否操作成功
     * 此处使用rose框架的rest风格url，可以把参数作为路径的一部分进行传递
     */
//	 @Before(Tx.class)
	public void update() {
        boolean flag = Db.tx(new IAtom() {
            @Override
            public boolean run() throws SQLException {
            String userName = getAttr(Constants.USER_NAME);
            AuthRole role = getModel(AuthRole.class);
            role.set("optname",userName);
            boolean sFlag = role.update();
            String perms = getPara("permIds");
            String strDelSql = "delete from auth_role_permission where roleid=?";
            Db.update(strDelSql,role.getId());
            if(sFlag && StringKit.notBlank(perms)){
                String [] permIds = perms.split(",");
                String sql="insert into auth_role_permission(roleid, permissionid,optname) values (?,?,?)";
                int count = permIds.length;
                Object[][] params = new Object[count][3];
                for(int i=0;i<count;i++){
                    params[i][0]=role.getId();
                    params[i][1]=permIds[i];
                    params[i][2]=userName;
                }
                Db.batch(sql, params, count);
            }
            return sFlag;
            }
        });
        if(flag){
     //       renderJson(Constants.EDITSUCCESS);
			render(new JsonRender(Constants.EDITSUCCESS).forIE());

        }else{
        //    renderJson(Constants.EDITFAILED);
			render(new JsonRender(Constants.EDITFAILED).forIE());

        }
	}
	
	/**
     * Post请求的菜单删除函数，可以接受菜单的id，并根据菜单进行物理删除，并返回影响行数，据此判断是否操作成功
     * 在删除角色数据的时候，需要顺带删除所赋予的权限
     */
	public void delete() {
        boolean flag = Db.tx(new IAtom() {
            @Override
            public boolean run() throws SQLException {
            boolean dFlag = AuthRole.dao.deleteById(getParaToInt());
            boolean rFlag = Db.deleteById("auth_role_permission","roleid",getParaToInt());
            return dFlag && rFlag;
            }
        });
        if(flag){
      //      renderJson(Constants.DELETESUCCESS);
			render(new JsonRender(Constants.DELETESUCCESS).forIE());

        }else{
        //    renderJson(Constants.DELETEFAILED);
			render(new JsonRender(Constants.DELETEFAILED).forIE());

        }
	}

    public void permsTree(){
        AuthUser u = getSessionAttr(Constants.LOGIN_USER);
        if(u!=null){
            String roleId = getPara(0);
            List<String> permList = null;
            if(StringKit.notBlank(roleId)){
                String permSql = "select permissionid from auth_role_permission where roleid=?";
                permList = Db.query(permSql,roleId);
            }

            List<Record> list;
            if(u.getUsername().equals("admin")){
                String strSql = "select id, name as text,pid from auth_permission order by disp";//where pid=0
                list = Db.find(strSql);
            }else{
                String strSql = "select a.id, a.name as text from auth_permission a,auth_role_permission b where b.roleid in(select roleid from auth_user_role where userid=?) and a.id = b.permissionid order by a.disp"; //a.pid=0 and
                list = Db.find(strSql,u.getId());
            }
            List<Record> listAll = queryPerms(list,permList,0);

            renderJson(listAll);
        }
    }

    public void userpermsTree(){
        AuthUser u = getSessionAttr(Constants.LOGIN_USER);
        if(u!=null){
            String roleId = getPara(0);
            List<String> permList = null;
            if(StringKit.notBlank(roleId)){
                String permSql = "select permissionid from auth_user_permission where userid=?";
                permList = Db.query(permSql,roleId);
            }

            List<Record> list;
            if(u.getUsername().equals("admin")){
                String strSql = "select id, name as text,pid from auth_permission order by disp";//where pid=0
                list = Db.find(strSql);
            }else{
                String strSql = "select a.id, a.name as text from auth_permission a,auth_role_permission b where b.roleid in(select roleid from auth_user_role where userid=?) and a.id = b.permissionid order by a.disp"; //a.pid=0 and
                list = Db.find(strSql,u.getId());
            }
            List<Record> listAll = null;
           if(list.size()>0){
               listAll = queryPerms(list,permList,0);
                }
//            System.out.println("+============================================="+list );
//            System.out.println("+============================================="+permList );

            renderJson(listAll);
        }
    }
    /**
     * queryPerms菜单递归函数
     * @param _list
     * @return
     */
    private List<Record> queryPerms(List<Record> _list,List<String> perms,int pid) {
        List<Record> retList = new ArrayList<Record>();
        for (Record r : _list) {
              //  是 子节点再勾选
            if(pid == r.getInt("pid")){
                List<Record> l = queryPerms(_list, perms, r.getInt("id"));
                if (l.size() > 0) {
                    r.set("children", l);
                }   else {
                    if(perms!=null && perms.contains(r.get("id")) && !r.get("pid").equals(0)){
                        r.set("checked", true);
                    }else{
                        r.set("checked", false);
                    }
                }
                retList.add(r);
            }
        }

        return retList;
    }
}

